package org.demo.multisource.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.apache.ibatis.mapping.DatabaseIdProvider;

import javax.sql.DataSource;

public class MybatisUtil {

    public static String databaseId(){
        try {
            DatabaseIdProvider databaseIdProvider = SpringUtil.getBean(DatabaseIdProvider.class);
            if(databaseIdProvider!=null) {
                DataSource dataSource = SpringUtil.getBean(DataSource.class);
                if(dataSource instanceof DynamicRoutingDataSource) {
                    return databaseIdProvider.getDatabaseId(((DynamicRoutingDataSource)dataSource).determineDataSource());
                }
                return databaseIdProvider.getDatabaseId(dataSource);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
